﻿Imports System.Net
Imports System.IO

Module DownloadTools
    Dim objWebRequest As HttpWebRequest
    Dim obhWebResponse As HttpWebResponse
    Dim lonLength As Long = 0
    Dim objFileStream As IO.FileStream

    Dim CursorTop As Integer
    Dim CursorLeft As Integer

    Public Sub DL(URL As String)
        CursorTop = Console.CursorTop
        CursorLeft = Console.CursorLeft
        DrawProgresBar()

        If File.Exists(_DefaultAppDirectory & "\tmp.7z") Then File.Delete(_DefaultAppDirectory & "\tmp.7z")

        Try
            objWebRequest = WebRequest.Create(URL)
            obhWebResponse = objWebRequest.GetResponse
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Exit Sub
        End Try
        lonLength = obhWebResponse.ContentLength
        Try
            objFileStream = New FileStream(_DefaultAppDirectory & "\tmp.7z", IO.FileMode.Create)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Exit Sub
        End Try
        Dim NR As Long
        Dim ST As New Stopwatch
        Dim CS As Double = -1
        Dim R As Integer
        Do
            ST.Start()
            Dim RB(4095) As Byte
            Dim BR As Integer = obhWebResponse.GetResponseStream.Read(RB, 0, 4096)
            NR += BR
            Dim P As Short = (NR * 100) / lonLength
            PB(P, CS, lonLength, NR)
            If BR = 0 Then Exit Do

            objFileStream.Write(RB, 0, BR)
            ST.Stop()
            R += 1
            If R >= 100 Then
                CS = 20480 / (ST.ElapsedMilliseconds / 1000)
                ST.Reset()
                R = 0
            End If
        Loop

        obhWebResponse.GetResponseStream.Close()
        objFileStream.Close()

        SetConsoleColors(ConsoleColor.grey)
        Console.SetCursorPosition(0, 4)
    End Sub
    Private Sub PB(percent As Integer, speed As Double, len As Long, ReadNumber As Long)
        UpdateProgresBar(percent, ConsoleColor.red)

        Console.SetCursorPosition(0, 3)
        Console.Write("{0,-25}", "Size: " & Math.Round(len / 1024) & " kb")
        Console.Write("{0,-25}", "Speed: " & Math.Round(speed / 1024) & " kb/s")
        Console.Write("{0,-25}", "Read Number: " & ReadNumber)
    End Sub

    


    



End Module
